// handlers/VideoHandler.js
const BaseHandler = require('./BaseHandler');
const fs = require('fs');
const path = require('path');

class VideoHandler extends BaseHandler {
    async handle(req, res, filePath) {
        try {
            if (!await this.fileExists(filePath)) {
                return this.sendError(res, 404, 'Video file not found');
            }

            const stat = await fs.promises.stat(filePath);
            const fileSize = stat.size;
            const range = req.headers.range;

            // 获取文件扩展名以确定Content-Type
            const ext = path.extname(filePath).toLowerCase();
            const contentType = this.getVideoContentType(ext);

            // 设置通用的响应头
            res.setHeader('Content-Type', contentType);
            res.setHeader('Accept-Ranges', 'bytes');
            res.setHeader('Cache-Control', 'public, max-age=3600'); // 视频缓存1小时

            if (range) {
                // 处理范围请求（支持拖拽和跳转）
                const parts = this.parseRangeHeader(range, fileSize);

                if (parts) {
                    const [start, end] = parts;
                    const chunksize = (end - start) + 1;

                    const headers = {
                        'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                        'Content-Length': chunksize,
                    };

                    res.writeHead(206, headers);

                    // 创建文件流并传输指定范围的数据
                    const fileStream = fs.createReadStream(filePath, {
                        start,
                        end,
                        highWaterMark: 64 * 1024 // 64KB chunks
                    });

                    fileStream.on('error', (error) => {
                        console.error('Video stream error:', error);
                        if (!res.headersSent) {
                            this.sendError(res, 500, 'Video streaming error');
                        }
                    });

                    fileStream.pipe(res);

                } else {
                    // 范围请求无效，返回整个文件
                    res.writeHead(200, {
                        'Content-Length': fileSize
                    });
                    fs.createReadStream(filePath).pipe(res);
                }
            } else {
                // 没有范围请求，返回整个文件
                res.writeHead(200, {
                    'Content-Length': fileSize
                });

                const fileStream = fs.createReadStream(filePath);
                fileStream.on('error', (error) => {
                    console.error('Video stream error:', error);
                    if (!res.headersSent) {
                        this.sendError(res, 500, 'Video streaming error');
                    }
                });

                fileStream.pipe(res);
            }

        } catch (error) {
            console.error('Error streaming video:', error);
            if (!res.headersSent) {
                this.sendError(res, 500, 'Failed to stream video');
            }
        }
    }

    parseRangeHeader(range, fileSize) {
        if (!range) return null;

        const parts = range.replace(/bytes=/, "").split("-");
        const start = parseInt(parts[0], 10);
        const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;

        // 验证范围有效性
        if (isNaN(start) || isNaN(end) || start >= fileSize || end >= fileSize || start > end) {
            return null;
        }

        return [start, end];
    }

    getVideoContentType(ext) {
        const contentTypes = {
            '.mp4': 'video/mp4',
            '.avi': 'video/x-msvideo',
            '.mkv': 'video/x-matroska',
            '.mov': 'video/quicktime',
            '.wmv': 'video/x-ms-wmv',
            '.flv': 'video/x-flv',
            '.webm': 'video/webm',
            '.m4v': 'video/x-m4v',
            '.3gp': 'video/3gpp'
        };

        return contentTypes[ext] || 'video/mp4';
    }
}

module.exports = VideoHandler;